package cn.edu.swu.auth;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        HttpSession session = request.getSession(true);

        // 检查验证码
        String authcode = (String) session.getAttribute(AuthCodeServlet.AUTH_CODE);
        if (authcode == null || !authcode.equalsIgnoreCase(code)) {
            response.sendRedirect("./login.html");
            return;
        }

        if (username == null || username.trim().isEmpty() || password == null || password.trim().isEmpty()) {
            response.sendRedirect("login.html?error=用户名和密码不能为空");
            return;
        }

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        String jdbcURL = "jdbc:mysql://localhost:3306/bookstore";
        String jdbcUsername = "root";
        String jdbcPassword = "zmj410310";

        // 连接数据库并验证用户
        try (Connection connection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
             PreparedStatement pstmt = connection.prepareStatement("SELECT * FROM users WHERE username = ? AND password = ?")) {

            pstmt.setString(1, username);
            pstmt.setString(2, password); // 实际应用中应该使用加密密码进行比较

            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    // 用户名和密码匹配，设置session属性
                    int userId = rs.getInt("id");
                    session.setAttribute("userId", userId); // 登录成功后获取用户id并存储在会话中，以便实现购物车和统计在线用户人数的功能
                    response.sendRedirect("./page.html"); // 重定向到主页或其他页面
                } else {
                    response.sendRedirect("./login.html?error=用户名或密码错误");
                }
            }
        } catch (SQLException e) {
            throw new ServletException("Database error while logging in user", e);
        }
    }
}